package visualizer.google;

import java.util.HashMap;
import java.util.Iterator;
import java.util.NoSuchElementException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class GoogleResponse {
	private JSONObject data;
	
	public GoogleResponse(JSONObject data)
	{
		this.data = data;
	}
	
	public boolean isSuccess()
	{
		return getStatus() == 200;
	}
	
	public String getDetails()
	{
		try {
			return data.getString("responseDetails");
		} catch (JSONException e) {
			return "";
		}
	}
	
	public int getStatus()
	{
		try {
			return data.getInt("responseStatus");
		} catch (JSONException e) {
			return -1;
		}
	}
	
	public int getEstimatedResultCount()
	{
		try {
			return data.getJSONObject("responseData")
			           .getJSONObject("cursor")
			           .getInt("estimatedResultCount");
		} catch (JSONException e) {
			return -1;
		}
	}
	
	public SearchResultCollection getResults()
	{
		try {
			return new SearchResultCollection(data.getJSONObject("responseData").getJSONArray("results"));
		} catch (JSONException e) {
			return new SearchResultCollection(getEmptyResultArray());
		}
	}
	
	private JSONArray getEmptyResultArray() {
		return new JSONArray();
	}

	public class SearchResultCollection implements Iterable<SearchResult>
	{
		private JSONArray results;
		public SearchResultCollection(JSONArray results) {
			this.results = results;
		}
		
		public Iterator<SearchResult> iterator() {
			return new SearchResultCollectionIterator(results);
		}
	}
	
	public class SearchResultCollectionIterator implements Iterator<SearchResult>
	{
		private JSONArray results;
		private int position = 0;
		
		public SearchResultCollectionIterator(JSONArray results) {
			this.results = results;
		}
		
		public boolean hasNext() {
			return position < results.length();
		}
		
		public SearchResult next() {
			try {
				return new SearchResult(results.getJSONObject(position++));
			} catch (JSONException e) {
				throw new NoSuchElementException();
			}
		}
		
		public void remove() {
			throw new UnsupportedOperationException();
		}
	}
	
	public class SearchResult {
		private JSONObject data;
		
		public SearchResult()
		{
			this.data = new JSONObject();
		}
		
		public SearchResult(JSONObject data)
		{
			this.data = data;
		}
		
		public String getTitle()
		{
			try {
				return data.getString("title");
			} catch (JSONException e) {
				return "";
			}
		}
		
		public String getContent()
		{
			try {
				return data.getString("content");
			} catch (JSONException e) {
				return "";
			}
		}
	}
}
